<?php

namespace app\api\service\user;

use app\common\model\user\User;
use think\facade\Cache;

class UserService
{
    /**
     * 记忆上门自提联系人
     */
    public static function setLastExtract($userId, $linkman, $phone)
    {
        // 缓存时间30天
        $expire = 86400 * 30;
        return Cache::set("{$userId}_LastExtract", compact('linkman', 'phone'), $expire);
    }

    /**
     * 记忆上门自提联系人
     */
    public static function getLastExtract($userId)
    {
        if ($lastExtract = Cache::get("{$userId}_LastExtract")) {
            return $lastExtract;
        }
        return ['linkman' => '', 'phone' => ''];
    }

    /**
     * 获取上级（3层）
     */
    public static function getAgents($userId, $level = 3)
    {
        static $agents = [];
        if (empty($agents) || empty($agents[$userId])) {
            $user = User::find($userId);
            while ($user && $level--) {
                $up_id = $user->referee_id;
                if ($up_id) {
                    $user = User::find($up_id);
                    $agents[$userId][] = $user;
                } else {
                    break;
                }
            }
        }
        if (empty($agents)) {
            return [];
        }
        return $agents[$userId];
    }
}